/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.worldscale.xp.wslib.im.jabber.impl;

/**
 *
 * @author Kun
 */
public class Base64 {

    public final static String BASE_64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    private static char[] sBase64Alphabet = null;

    private static char[] getBase64Alphabet() {
        if (sBase64Alphabet == null) {
            sBase64Alphabet = BASE_64_ALPHABET.toCharArray();
        }
        return sBase64Alphabet;
    }

    public static String encode(final byte[] buf, final int begin, final int cb) {
        final char[] alpha = getBase64Alphabet();
        final StringBuffer sbuf = new StringBuffer();
        final int end = begin + cb;
        int buffer, cbinbuf, cntCharOut;
        buffer = cbinbuf = cntCharOut = 0;
        for (int i = begin; i < end; i++) {
            // write to buffer
            buffer <<= 8;
            buffer |= (0xff & buf[i]);
            cbinbuf += 8;
            // read from buffer
            while (cbinbuf >= 6) {
                final int b64 = (buffer >> (cbinbuf - 6)) & 0x3f;
                cbinbuf -= 6;
                sbuf.append(alpha[b64]);
                cntCharOut++;
                if ((cntCharOut % 76) == 0) {
                    sbuf.append('\n');
                }
            }
        }
        if (0 < cbinbuf) {
            final int b64 = (buffer << (6 - cbinbuf)) & 0x3f;
            sbuf.append(alpha[b64]);
            cntCharOut++;
            if ((cntCharOut % 76) == 0) {
                sbuf.append('\n');
            }
        }
        int tail = (cb % 3);
        if (0 < tail) {
            for (; tail < 3; tail++) {
                sbuf.append('=');
                cntCharOut++;
                if ((cntCharOut % 76) == 0) {
                    sbuf.append('\n');
                }
            }
        }
        return sbuf.toString();
    }

    public static byte[] decode(String str) {
        return null;
    }
}
